package com.atguigu.wechat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.auth.service.OaProcessService;
import com.atguigu.auth.service.OaProcessTemplateService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.model.process.Process;
import com.atguigu.model.process.ProcessTemplate;
import com.atguigu.model.system.SysUser;
import com.atguigu.security.custom.LoginUserInfoHelper;
import com.atguigu.wechat.service.MessageService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Map;

/**
 * ClassName: MessageServiceImpl
 * Package: com.atguigu.wechat.service.impl
 * Description:
 *
 * @Author 蹇泽阳
 * @Create 2023/11/23 15:24
 * @Version 1.0
 */
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {
  @Resource
  private WxMpService wxMpService;
  @Resource
  private OaProcessService processService;
  @Resource
  private OaProcessTemplateService processTemplateService;
  @Resource
  private SysUserService sysUserService;
  
  @SneakyThrows
  @Override
  public void pushPendingMessage(Long processId, Long userId, String taskId) {
    // 查询流程信息
    Process process = processService.getById(processId);
    // 查询审批模版信息
    ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
    // 根据userid查询要推送人信息
    SysUser sysUser = sysUserService.getById(userId);
    SysUser submitSysUser = sysUserService.getById(process.getUserId());
    String openid = sysUser.getOpenId();
    // 方便测试，给默认值（开发者本人的openId）
    // 获取要推送人的openid
    if (StringUtils.isEmpty(openid)) {
      openid = "omwf25izKON9dktgoy0dogqvnGhk";
    }
    // 设置消息发送信息
    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
        .toUser(openid)// 要推送的用户openid
        .templateId("rNGTrDfIDRHvjaLCqVsD89fCCZZ6aG3-i2zslRm7wG8") // 模板id,https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
        .url("http://jian2.free.idcfengye.com/#/show/" + processId + "/" + taskId)// 点击模板消息要访问的网址，9090对应的域名
        .build();
    
    JSONObject jsonObject = JSON.parseObject(process.getFormValues());
    JSONObject formShowData = jsonObject.getJSONObject("formShowData");
    StringBuffer content = new StringBuffer();
    for (Map.Entry entry : formShowData.entrySet()) {
      content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
    }
    // 填写模版变量对应的内容
    templateMessage.addData(new WxMpTemplateData("first",
        submitSysUser.getName() + "提交了" +
            processTemplate.getName() + "审批申请，请注意查看。", "#272727"));
    templateMessage.addData(new WxMpTemplateData("keyword1",
        process.getProcessCode(), "#272727"));
    templateMessage.addData(new WxMpTemplateData("keyword2",
        new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
    templateMessage.addData(new WxMpTemplateData("content",
        content.toString(), "#272727"));
    String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    log.info("推送消息返回：{}", msg);
  }
  
  @SneakyThrows
  @Override
  public void pushProcessedMessage(Long processId, Long userId, Integer status) {
    Process process = processService.getById(processId);
    ProcessTemplate processTemplate = processTemplateService.getById(process.getProcessTemplateId());
    SysUser sysUser = sysUserService.getById(userId);
    SysUser currentSysUser = sysUserService.getById(LoginUserInfoHelper.getUserId());
    String openid = sysUser.getOpenId();
    if (StringUtils.isEmpty(openid)) {
      openid = "omwf25izKON9dktgoy0dogqvnGhk"; // 方便测试，给默认值（开发者本人的openId）
    }
    WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
        .toUser(openid)// 要推送的用户openid
        .templateId("hjJkUeROdCRo7CdbXnFaHwecH6xgir-wJeRXkxNTbLs") // 模板id，https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
        .url("http://jian2.free.idcfengye.com/#/show/" + processId + "/0") // 点击模板消息要访问的网址，9090对应的域名
        .build();
    JSONObject jsonObject = JSON.parseObject(process.getFormValues());
    JSONObject formShowData = jsonObject.getJSONObject("formShowData");
    StringBuffer content = new StringBuffer();
    for (Map.Entry entry : formShowData.entrySet()) {
      content.append(entry.getKey()).append("：").append(entry.getValue()).append("\n ");
    }
    templateMessage.addData(new WxMpTemplateData("first", "你发起的" + processTemplate.getName() + "审批申请已经被处理了，请注意查看。", "#272727"));
    templateMessage.addData(new WxMpTemplateData("keyword1", process.getProcessCode(), "#272727"));
    templateMessage.addData(new WxMpTemplateData("keyword2", new DateTime(process.getCreateTime()).toString("yyyy-MM-dd HH:mm:ss"), "#272727"));
    templateMessage.addData(new WxMpTemplateData("keyword3", currentSysUser.getName(), "#272727"));
    templateMessage.addData(new WxMpTemplateData("keyword4", status == 1 ? "审批通过" : "审批拒绝", status == 1 ? "#009966" : "#FF0033"));
    templateMessage.addData(new WxMpTemplateData("content", content.toString(), "#272727"));
    String msg = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
    log.info("推送消息返回：{}", msg);
  }
}
